<template>
    <div class="video-page" v-if="westernMedicineDialog">
        <!--西药处方弹框 -->
        <el-dialog class="dialog-frame dialog-western" :visible.sync="westernMedicineDialog" @close="closeDialog('westernMedicineDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>{{isWesternChinese == 1 ? '中药处方' : '西药处方'}}</span>
            </div>
            <div v-loading.lock="dialogLoading || addLoading" element-loading-text="" element-loading-background="rgba(#fff, .5)" element-loading-spinner="el-icon-loading">
                <div class="western-left">
                    <div v-if="isEditFlag">
                        <span class="patient-msg">姓名：{{drugOrderMsg.patientName}}</span>
                        <span class="patient-msg">性别：{{drugOrderMsg.patientSex}}</span>
                        <span class="patient-msg">年龄：{{drugOrderMsg.patientAge}}</span>
                    </div>
                    <el-tabs v-model="westernActiveName" @tab-click="handleWesternClick">
                        <el-tab-pane label="药品目录" name="1"></el-tab-pane>
                        <el-tab-pane label="个人用药" name="2"></el-tab-pane>
                        <el-tab-pane label="公用模板" name="3"></el-tab-pane>
                        <el-tab-pane label="个人模板" name="4"></el-tab-pane>
                        <el-tab-pane label="历史处方" name="5"></el-tab-pane>
                    </el-tabs>
                    <div class="chatroom-drug-search">
                        <div class="search__left">
                            <template v-if="!isEditFlag">
                                <el-select v-if="westernActiveName == '1' && !($global.platform('zh') && paymentId == 2) && !($global.platform('lj') && storeRadio == 'ljyn')" class="search__item o-select" v-model="drugClassSearch" placeholder="请选择药品类别" size="small" @change="getWesternDataList({page: 1}, storeRadio)">
                                    <el-option value="" label="请选择药品类别"></el-option>
                                    <el-option v-for="(item,index) in drugClassList" :key="index" :label="item.className" :value="item.id">
                                    </el-option>
                                </el-select>
                                <el-select v-if="!($global.isYiBao && paymentId == 2)" class="search__item o-select" size="small" v-model="storeRadio" filterable @change="changeStore(storeRadio)">
                                    <el-option label="全部药店" value=""></el-option>
                                    <el-option v-if="$global.platform('lj') && !isSub" label="院内药房" value="ljyn"></el-option>
                                    <el-option v-for="(item,index) in storeList" :key="index" :label="item.group_name" :value="item.group_no"></el-option>
                                </el-select>
                            </template>
                        </div>
                        <div class="search__right">
                            <el-input v-if="westernActiveName == '1'" class="o-input" v-model="drugNameSearch" size="small" clearable @clear="getWesternDataList({page: 1},storeRadio)">
                                <el-button slot="append" size="small" @click="getWesternDataList({page: 1},storeRadio)">搜索</el-button>
                            </el-input>
                            <div v-else class="chatroom-drug-tips">生成处方的药品来源须一致</div>
                        </div>
                    </div>
                    <div v-if="westernActiveName == '1'" class="chatroom-drug-tips">生成处方的药品来源须一致</div>
                    <!-- 西药处方--药品目录&个人用药 start-->
                    <el-table v-if="westernActiveName == '1' || westernActiveName == '2'" class="l-table" :data="westernDataList" border max-height="300" highlight-current-row>
                        <template v-if="$global.platform('zh') && paymentId == 2">
                            <el-table-column prop="name" label="名称">
                                <template slot-scope="scope">
                                    <span>{{scope.row.name || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="norms" label="规格">
                                <template slot-scope="scope">
                                    <span>{{scope.row.norms || '-'}} </span>
                                </template>
                            </el-table-column>
                        </template>
                        <template v-else>
                            <el-table-column prop="storeName" label="来源">
                                <template slot-scope="scope">
                                    <span v-if="storeRadio == 'ljyn'">院内药房</span>
                                    <span v-else>{{scope.row.storeName || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="isWesternChinese == 1" prop="drugCompany" label="厂商">
                                <template slot-scope="scope">
                                    <span>{{scope.row.drugCompany || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="drugName" label="名称">
                                <template slot-scope="scope">
                                    <span>{{scope.row.drugName || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="storeRadio == 'ljyn'" prop="dosageName" label="剂型">
                                <template slot-scope="scope">
                                    <span>{{scope.row.dosageName || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="isWesternChinese == 2" prop="drugSpecifications" label="规格">
                                <template slot-scope="scope">
                                    <span v-if="storeRadio == 'ljyn'">{{scope.row.packageSpec || '-'}} </span>
                                    <span v-else>{{scope.row.drugSpecifications || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="isWesternChinese == 1" prop="alias" label="别名">
                                <template slot-scope="scope">
                                    <span>{{scope.row.alias || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="isWesternChinese == 1" prop="placeOrigin" label="产地">
                                <template slot-scope="scope">
                                    <span>{{scope.row.placeOrigin || '-'}} </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="drugPrice" label="参考价格">
                                <template slot-scope="scope">
                                    <span v-if="storeRadio == 'ljyn'">{{scope.row.retailPrice || '-'}} </span>
                                    <span v-else>{{scope.row.drugPrice || '-'}} </span>
                                </template>
                            </el-table-column>
                        </template>
                        <el-table-column label="操作" width="100" v-if="!(westernActiveName == '2' && $global.platform('zh') && paymentId == 2)">
                            <template slot-scope="scope">
                                <span class="table-btn-size" @click="checkDrugSpeciFicationDetail(scope.row)">详情</span>
                                <span v-if="!isEditFlag" class="table-btn-size" @click="checkDrugDisable(scope.row,'add')">开药</span>
                                <p v-if="westernActiveName == '1' && !($global.platform('zh') && paymentId == 2) && storeRadio != 'ljyn'" class="table-btn-size" @click="saveDrugSingle(scope.row)">保存用药</p>
                                <p v-if="westernActiveName == '2'" class="table-btn-size table-btn-del" @click="deletePersonalDrug(scope.row)">删除</p>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination v-if="westernActiveName == '1' || westernActiveName == '2'" style="text-align:center;margin:15px 25px;" @current-change="changeWesternDataCurrent" :current-page="westernDataPage.current" :page-size="westernDataPage.size" layout="prev, pager, next,total" :total="westernDataPage.total">
                    </el-pagination>
                    <!-- 西药处方--药品目录&个人用药 end-->

                    <!-- 西药处方--个人模板&公用模板 -->
                    <el-table v-if="westernActiveName == '3' || westernActiveName == '4'" class="l-table" :data="westernModelList" border max-height="300" highlight-current-row>
                        <el-table-column prop="icdId" label="关联ICD">
                            <template slot-scope="scope">
                                <span>{{scope.row.icdId || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="diagnosisName" label="诊断名称">
                            <template slot-scope="scope">
                                <span>{{scope.row.diagnosisName || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="prescriptionName" label="模板别名">
                            <template slot-scope="scope">
                                <span>{{scope.row.prescriptionName || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="remarks" label="备注">
                            <template slot-scope="scope">
                                <span>{{scope.row.remarks || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="storeName" label="来源">
                            <template slot-scope="scope">
                                <!-- <span>{{ scope.row.drugList[0].storeName || '暂无'}} </span> -->
                                <span>{{scope.row.storeName || '暂无'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="130">
                            <template slot-scope="scope">
                                <span v-if="!isEditFlag && !($global.platform('zh') && paymentId == 2) && storeRadio != 'ljyn' && scope.row.storeId != 0" class="table-btn-size" @click="quoteDrugDetail(scope.row,1)">引用处方</span>
                                <p>
                                    <span class="table-btn-size" @click="getOpenedPrescriptionInfo(scope.row,1)">查看模板</span>
                                    <span class="table-btn-size table-btn-del" @click="deletePrescriptionTemplate(scope.row)">删除</span>
                                </p>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 西药处方--历史处方 -->
                    <el-table v-if="westernActiveName == '5'" class="l-table" :data="historyWesternList" border max-height="300" highlight-current-row>
                        <el-table-column prop="createTime" label="处方日期">
                            <template slot-scope="scope">
                                <span>{{scope.row.createTime || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="diagnosis" label="诊断名称">
                            <template slot-scope="scope">
                                <span>{{scope.row.diagnosisDescribe || '-'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="storeName" label="来源">
                            <template slot-scope="scope">
                                <span>{{scope.row.storeName || '暂无'}} </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150">
                            <template slot-scope="scope">
                                <span v-if="!isEditFlag && !($global.platform('zh') && paymentId == 2) &&  storeRadio != 'ljyn' && scope.row.storeId != 0" class="table-btn-size" @click="quoteDrugDetail(scope.row,2)">引用处方</span>
                                <span class="table-btn-size" @click="getOpenedPrescriptionInfo(scope.row,2)">查看处方</span>
                                <!-- <p class="table-btn-size" @click="openPrescriptionDialog">另存模板</p> -->
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="western-right">
                    <h3 class="western-title">开{{isWesternChinese == 1 ? '中药处方' : '西药处方'}}</h3>
                    <div class="western-right-content">
                        <span>诊断</span>
                        <div style="float:right;cursor:pointer;" @click="openDiagnosisDialog(patientList.diagnosisArray)" v-if="!isEditFlag">编辑</div>
                        <div class="dialog-content" style="min-height: 50px;">
                            <template v-if="!isEditFlag">
                                <span v-for="(item, index) in patientList.diagnosisArray" :key="index">
                                    <span v-if="index !== 0">,</span>
                                    {{item.diagnosis}}
                                </span>
                            </template>
                            <span v-if="isEditFlag">
                                {{diagnosisArray}}
                            </span>
                        </div>
                    </div>
                    <div class="western-right-content">
                        <span>RP</span>
                        <div v-show="!($global.platform('zh') && paymentId == 2) && !(storeRadio == 'ljyn' || alreadyHasHis)" style="float:right">参考价格：￥<span>{{referencePrice || '0.00'}}</span></div>
                        <div class="dialog-content drug-content">
                            <div class="content-list" v-for="(item,index) in alreadydDrugList" :key="index">
                                <p class="content-name">{{item.drugName}}
                                    <span class="table-btn-del table-btn-size" style="font-size:16px;"><i class="el-icon-close" @click="delectPrescription(item)"></i></span>
                                    <span class="table-btn-size" @click="checkDrugDisable(item,'edit')"><i class="el-icon-edit"></i></span>
                                </p>
                                <p>
                                    <span>{{item.detailsUsage}}</span>
                                    <span> <span v-if="isWesternChinese == 2">每次</span> {{item.detailsConsumption}}{{item.detailsConsumptionUnit}}</span>
                                    <span v-if="isWesternChinese == 2">用药{{item.detailsDay}}天</span>
                                </p>
                                <p v-show="!($global.platform('zh') && paymentId == 2)" class="drug-store">
                                    来源：
                                    {{ $global.platform('lj') && item.storeId == 0 ? '院内药房' : item.storeName }}
                                </p>
                            </div>
                            <div style="position:absolute;bottom:8px;right:24px;">
                                <el-button v-if="!isEditFlag && !($global.platform('zh') && paymentId == 2) && !(storeRadio == 'ljyn' || alreadyHasHis)" type="primary" size="small" plain @click="openPrescriptionDialog">另存为个人模板</el-button>
                                <el-button :loading="addLoading" type="primary" size="small" @click="addPrescriptionModel">{{!isEditFlag ? '生成处方' : '确认修改'}}</el-button>
                            </div>
                        </div>
                    </div>
                    <div class="western-right-content" v-if="!isEditFlag">
                        <span>已开{{isWesternChinese == 1 ? '中药处方' : '西药处方'}}</span>
                        <div class="drugList-content">
                            <ul v-loading="historyListLoading" element-loading-text="加载中" element-loading-background="rgba(255,255,255,.7)">
                                <li style="position: relative;" v-for="(item,index) in openWesternList" :key="index">
                                    {{item.prescriptionNo}}
                                    <span style="position: absolute;right: 0px;top: 0;">
                                        <span class="table-btn-size" @click="check(item)">详情</span>
                                        <span v-if="!isEditFlag" class="table-btn-size table-btn-del" @click="deletePrescription(item)">删除</span>
                                    </span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>


        <!-- 西药处方--查看处方弹框 start-->
        <el-dialog class="dialog-frame" width="600" :visible.sync="prescriptionInfoListDialog" @close="closeDialog('prescriptionInfoListDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>查看处方</span>
            </div>
            <div v-if="isViewPrescription == false">
                <p><span>诊断名称：</span>{{drugHisInfoList.diagnosisName}}</p>
                <p><span>模板别名：</span>{{drugHisInfoList.prescriptionName}}</p>
                <p><span>备注：</span>{{drugHisInfoList.remarks}}</p>
            </div>
            <el-table class="l-table" :data="prescriptionInfoList" border max-height="300" highlight-current-row>
                <el-table-column prop="storeName" label="来源">
                    <template slot-scope="scope">
                        <span>{{scope.row.storeName || '-'}} </span>
                    </template>
                </el-table-column>
                <el-table-column prop="drugName" label="药品名称">
                    <template slot-scope="scope">
                        <span>{{scope.row.drugName || '-'}} </span>
                    </template>
                </el-table-column>
                <el-table-column prop="detailsConsumption" label="用量">
                    <template slot-scope="scope">
                        <span>{{scope.row.detailsConsumption || '-'}} </span>
                    </template>
                </el-table-column>
                <el-table-column prop="detailsFrequencyStr" label="频次">
                    <template slot-scope="scope">
                        <span>{{scope.row.detailsFrequencyStr || '-'}} </span>
                    </template>
                </el-table-column>
                <el-table-column prop="detailsDay" label="天数">
                    <template slot-scope="scope">
                        <span>{{scope.row.detailsDay || '-'}} </span>
                    </template>
                </el-table-column>
                <el-table-column prop="detailsUsage" label="用法">
                    <template slot-scope="scope">
                        <span>{{scope.row.detailsUsage || '-'}} </span>
                    </template>
                </el-table-column>
                <el-table-column prop="detailsEntrust" label="用药嘱咐">
                    <template slot-scope="scope">
                        <span>{{scope.row.detailsEntrust || '-'}} </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <span class="table-btn-size" @click="checkDrugSpeciFicationDetail(scope.row)">详情查看</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 西药处方--查看处方弹框 end -->

        <!--生成中药特殊提示弹框 start-->
        <el-dialog class="dialog-frame" width="600" :visible.sync="chineseDrugTipsDialog" @close="closeDialog('chineseDrugTipsDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>提示</span>
            </div>
            <el-form :model="drugChineseTipsForm" :rules="drugChineseTipsFormRule" ref="drugChineseTipsForm" label-position="left" label-width="80px">
                <el-form-item label="服用方法" prop="prescriptionTaking">
                    <el-select v-model="drugChineseTipsForm.prescriptionTaking" style="width:100%" placeholder="服用方法" @focus="getDrugUsageList(3)">
                        <template v-if="$global.platform('lj')">
                            <el-option v-for="(item,index) in hisDrugUsageList" :key="index" :label="item.dictName" :value="item.dictName"></el-option>
                        </template>
                        <template v-else>
                            <el-option v-for="(item,index) in drugUsageList" :key="index" :label="item.usageName" :value="item.usageName"></el-option>
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="!this.$global.platform('lj')" label="服用要求" prop="prescriptionRequirements">
                    <el-select v-model="drugChineseTipsForm.prescriptionRequirements" style="width:100%" placeholder="服用要求" @focus="getDrugUsageList(4)">
                        <el-option v-for="(item,index) in drugUsageList" :key="index" :label="item.usageName" :value="item.usageName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="付数(付)" prop="prescriptionNum">
                    <el-input type="text" v-model="drugChineseTipsForm.prescriptionNum" auto-complete="off" placeholder="付数" size="middle"></el-input>
                </el-form-item>
                <div style="text-align:center;margin-top:35px">
                    <el-button type="primary" size="small" @click="addChineseDrugTipsModel('drugChineseTipsForm')" :loading="addLoading">保 存</el-button>
                </div>
            </el-form>
        </el-dialog>
        <!--生成中药特殊提示弹框 end -->


        <!--西药处方--另存模版--选择ICD检索与处方模板 start -->
        <el-dialog class="dialog-frame dialog-choose" width="600" :visible.sync="addPrescriptionTemplateDialog" @close="closeDialog('addPrescriptionTemplateDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>另存个人模版</span>
            </div>
            <div style="text-align:center;">
                <div>
                    <span style="color:#fa6464;margin:0 5px 0 2px;">*</span>诊断名称
                    <el-input size="small" style="width: 220px;;margin-left:10px;" v-model="drugSaveICDInput" :disabled="true"></el-input>
                    <el-button type="primary" size="small" @click="openDialog('chooseICDSearchDialog','drug')">ICD检索</el-button>
                    <p style="color:#fa6464;margin:5px 10px 10px 10px;">
                        提示：通过ICD检索与处方模板进行关联。
                    </p>
                </div>
                <div>
                    <span style="color:#fa6464;margin:0 5px 0 2px">*</span>模板名称
                    <el-input v-model="drugSaveInput" style="width:300px;margin-left:10px;" size="small"></el-input>
                </div>
                <div>
                    <span>备注</span>
                    <el-input type="textarea" v-model="drugRemrakInput" style="margin:20px 0 0 50px;width:300px;" size="small"></el-input>
                </div>
                <el-button style="margin-top:20px;" type="primary" size="small" @click="saveAnotherModel">添加</el-button>
            </div>
        </el-dialog>

        <!--选择ICD检索与处方模板 start -->
        <el-dialog class="dialog-frame dialog-choose" width="600" :visible.sync="chooseICDSearchDialog" @close="closeDialog('chooseICDSearchDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>选择ICD检索与处方模板</span>
            </div>
            <div class="choose-ICDSearch">
                <div>
                    <span>ICD检索</span>
                    <el-input class="ICD-Search" size="small" v-model="healthICDSearch"></el-input>
                    <el-button type="primary" size="small" @click="getICDList">搜索</el-button>
                </div>
                <span>检索列表</span>
                <div class="dialog-content ICDSearch-list">
                    <p v-for="(item, index) in ICDlist" :key="index" @click="saveICDSearch(item)">{{item.icdName}}</p>
                </div>
                <div style="color:#fa6464;">提示：点击检索列表进行选择</div>
            </div>
        </el-dialog>
        <!--选择ICD检索与处方模板 end -->
        <!--西药处方--另存模版--选择ICD检索与处方模板 end -->


        <!-- 药品信息详情 -->
        <el-dialog class="dialog-frame drug-specification-dialog" width="300" :visible.sync="drugSpeciFicationDetailDialog" @close="closeDialog('drugSpeciFicationDetailDialog')" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="title-size">
                <div class="title-icon">
                    <img src="@/assets/img/img_decorate.png" alt="">
                </div>
                <span>药品信息</span>
            </div>
            <div>
                <div class="drugMap-img">
                    <img v-if="ficationDetailList.drugImg" :src="ficationDetailList.drugImg" alt="">
                </div>
                <div class="drugs-name drug-specifica">
                    <p class="name-size">
                        {{ $global.platform('lj') && storeRadio == 'ljyn' ? ficationDetailList.drugName :
                            $global.platform('zh') && paymentId == 2 ?  ficationDetailList.name : ficationDetailList.drugName }}
                    </p>
                    <p>
                        规格：
                        <!-- {{ficationDetailList.drugSpecifications|| ficationDetailList.norms || '-'}} -->
                        {{ $global.platform('lj') && storeRadio == 'ljyn' ? ficationDetailList.packageSpec :
                               $global.platform('zh') && paymentId == 2 ?  ficationDetailList.norms : ficationDetailList.drugSpecifications}}
                    </p>
                    <p>
                        参考价格：
                        {{ $global.platform('lj') && storeRadio == 'ljyn' ? ficationDetailList.retailPrice : ficationDetailList.drugPrice }}
                    </p>
                </div>
                <div class="drugs-name drug-specifica">
                    <p>
                        别名：
                        {{ ficationDetailList.alias }}
                    </p>
                    <p>通用名：{{ $global.platform('lj') && storeRadio == 'ljyn' ? ficationDetailList.drugCommonName : ficationDetailList.commonName}}</p>
                    <p>产地： {{ $global.platform('lj') && storeRadio == 'ljyn' ? ficationDetailList.productionPlace : ficationDetailList.drugOrigin}}</p>
                </div>
                <div class="drugs-name drug-specifica">
                    <!-- 珠海医院-医保付费 -->
                    <p v-if="$global.platform('zh') && paymentId == 2 ">药品类型：{{ficationDetailList.type || '-'}}</p>
                    <!-- 廉江-院内购药 -->
                    <p v-if="$global.platform('lj') && storeRadio == 'ljyn' ">药品类型：{{ficationDetailList.typeName || '-'}}</p>
                    <!-- 其他医院 -->
                    <p v-else>药品类型：{{ficationDetailList.drugType == '1' ? '中药': '西药' || '-'}}</p>

                    <p>来源：{{$global.platform('lj') && storeRadio == 'ljyn' ? '院内药房' : ficationDetailList.drugOrigin}}</p>
                    <p>厂商：
                        {{ $global.platform('lj') && storeRadio == 'ljyn' ? ficationDetailList.manufactorName :
                               $global.platform('zh') && paymentId == 2 ?  ficationDetailList.manufacturer : ficationDetailList.drugCompany}}
                    </p>
                </div>
                <div class="dialog-content">
                    {{ficationDetailList.drugInstructions || '暂无药品说明详情'}}
                </div>
            </div>
        </el-dialog>


        <pdf-dialog ref="pdfDialog" :has-save="false"></pdf-dialog>


        <!-- 诊断弹框  -->
        <diagnosis-dialog ref="diagnosisDialogComponent" @closed="val => closeDialogComponent(val,'diagnosisDialogComponent')"></diagnosis-dialog>

        <!-- --------- 开药 --------- -->
        <update-drug ref="updateDrug" @submited="saveDrugData"></update-drug>
    </div>
</template>

<script>
    import DiagnosisDialog from '@/views/videoroom/components/DiagnosisDialog';
    import pdfDialog from '@/components/chatroom/view-pdf';
    import drugDetail from '@/components/chatroom/drug-detail';
    import updateDrug from '@/components/chatroom/update-drug';

    export default {
        props: {
            isSub: {
                type: Boolean,
                default: false
            }, // 是否自主开方
        },
        components: {
            pdfDialog,
            'diagnosis-dialog': DiagnosisDialog,
            drugDetail,
            updateDrug
        },
        data() {
            var checkNum = (rule, value, callback) => { // 验证正整数
                const boolean = new RegExp('^[1-9][0-9]*$').test(value)
                if (!boolean) {
                    callback(new Error('请输入正整数'));
                } else {
                    callback();
                }
            };

            return {
                logId: '',
                inquiryPatientId: '',

                /* 中西药弹框start */
                westernMedicineDialog: false, //西药弹框
                prescriptionInfoListDialog: false, //西药--历史处方--查看详情
                addPrescriptionTemplateDialog: false, //西药--另存模板弹框
                chineseDrugTipsDialog: false, //生成中药特殊提示弹框
                chooseICDSearchDialog: false, //另存模板弹框
                drugSpeciFicationDetailDialog: false, //药品规范详情弹框
                isWesternChinese: '', //中药还是西药(1中药 2西药 不传则查全部)
                westernActiveName: '1',
                chineseActiveName: '1',
                westernDataList: [], //药品目录
                drugClassSearch: '', //下拉药品类别搜索
                drugClassList: [], //下拉药品搜索
                drugNameSearch: '', //药品列表搜索
                westernDataPage: { //药品规范分页
                    total: 0,
                    current: 1,
                    size: 50,
                },
                westernModelList: [], //西药个人&公用模板列表
                historyWesternList: [], //历史列表
                openWesternList: [], //已开处方
                historyListLoading: false, //历史列表加载
                prescriptionInfoList: [], //历史列表--查看详情
                drugChineseTipsForm: { //开处方药表单
                    prescriptionNum: '',
                    prescriptionTaking: '',
                    prescriptionRequirements: '',
                },
                drugChineseTipsFormRule: {
                    prescriptionTaking: [{ required: true, message: '服用方法不能为空', trigger: 'change' }],
                    prescriptionNum: [{ required: true, message: '付数不能为空', trigger: 'blur' }, { validator: checkNum, trigger: 'blur' }],
                },
                referencePrice: 0, //参考价格
                alreadydDrugList: [], //完成开药列表
                alreadydDrug: '', //已开药的名字
                alreadydDrugId: '', //已开药的id
                chooseDrugList: [], //当前选中开药药品的数据
                drugSaveInput: '', //中西药--另存个人模板名称input
                drugSaveICDInput: '', //中西药--另存个人模板诊断input
                drugSaveICDId: '', //中西药--另存个人模板诊断input
                drugRemrakInput: '', //中西药--另存个人模板备注input
                ICDTypeName: '', //ICD检索名称
                drugInfoList: {}, //药品详情
                drugHisInfoList: [], //历史处方--药品详情
                isViewPrescription: false, //历史处方--药品详情
                isEditPrescription: false, //开药是否编辑状态
                ICDlist: [], //icd列表
                diagnosisArray: '', //诊断列表
                drugUsageList: {}, //获取药品用法列表
                drugFrequencyList: [], //获取药品频次列表
                healthICDSearch: '', //健康指导--icd检索
                patientList: {}, //患者详情列表
                ficationDetailList: {}, //药品规范-详情按钮
                isEditOrNot: false, //是否编辑状态
                drugOrderId: null, //处方订单编号
                drugOrderMsg: {}, //处方订单信息
                addLoading: false, //生成处方加载
                isRepeat: false, //是否有重复开药操作
                frequencyList: [], //获取药品频次列表
                frequencyNum: '',
                storeList: [], //药店列表，
                storeRadio: '',
                shopId: '',
                dialogLoading: false,

                paymentId: '', // 付费类型
                useUnitArray: [], // 廉江his-用量单位选项
                hisDrugUsageList: [], // 廉江his - 中药用法
                hisDrugPrice: 0, // his-院内处方金额
                drugIsHis: false, // 当前药品为his
                alreadyHasHis: false, // 已选药品存在his
            }
        },
        methods: {
            // 打开弹框 // msg, isEdit, paymentMethod = ''
            onOpen({ data, isEdit, paymentMethod } = {}) {
                // paymentMethod,1=自费，2=医保
                this.isEditFlag = isEdit || false;

                if (!this.isEditFlag) { // 开处方药操作
                    this.logId = data.logId || '';
                    // this.diagnosisArray = data.diagnosisArray;
                    this.inquiryPatientId = data.inquiryPatientId || '';
                    this.getPatientInfo();
                    this.isWesternChinese = data.drugType || '';
                    this.alreadydDrugList = [];
                    this.referencePrice = 0
                    this.hisDrugPrice = 0;

                    this.paymentId = paymentMethod || '';
                    this.storeRadio = this.$global.platform('lj') && !this.isSub ? 'ljyn' : '';
                    this.changeStore(this.storeRadio);
                } else { // 编辑处方操作 
                    this.drugOrderId = data.drugId

                    let para = {
                        id: data.drugId
                    }

                    this.$ajax.editorPrescription(para).then(res => {
                        this.drugOrderMsg = res.data;
                        this.isWesternChinese = res.data.prescriptionType;
                        this.diagnosisArray = res.data.diagnosisDescribe;
                        this.referencePrice = res.data.prescriptionPrice || 0;
                        this.alreadydDrugList = res.data.prescriptionDrugListResps;
                        this.storeRadio = this.alreadydDrugList[0] && this.alreadydDrugList[0].storeId;

                        if (this.storeRadio == '0') this.storeRadio = 'ljyn'
                        this.changeStore(this.storeRadio);
                    }).catch(err => {
                        this.$util.message(err.msg);
                    })
                }

                this.westernMedicineDialog = true;
                this.westernActiveName = '1';
                this.drugNameSearch = '';

                setTimeout(() => {
                    this.getDrugClass();
                    this.getOpenedPrescription();
                    this.getStoreList();
                }, 500)
            },
            handleWesternClick(tab, event) { //西药处方tab
                this.westernActiveName = tab.name;

                if (!this.isEditFlag) {
                    if (this.$global.platform('lj') && !this.isSub) {
                        this.storeRadio = 'ljyn';
                    } else {
                        this.storeRadio = '';
                    }
                } else {
                    this.storeRadio = this.alreadydDrugList[0] && this.alreadydDrugList[0].storeId || '';
                }


                if (tab.name == '1' || tab.name == '2') {
                    this.getWesternDataList({ page: 1 }, this.storeRadio);
                } else if (tab.name == '3' || tab.name == '4') {
                    if (this.$global.platform('lj') && this.storeRadio == 'ljyn') {
                        this.westernModelList = [];
                    } else {
                        this.getPrescriptionTemplateList('');
                    }
                } else if (tab.name == '5') {
                    if (this.$global.platform('lj') && this.storeRadio == 'ljyn') {
                        this.historyWesternList = [];
                    } else {
                        this.getHisPrescription('');
                    }
                }
            },

            /*** 诊断弹框 start ***/
            openDiagnosisDialog(data = []) {
                this.$nextTick(() => {
                    this.$refs.diagnosisDialogComponent.onOpen({
                        logId: this.logId,
                        data
                    })
                })
            },
            closeDialogComponent(flag, refName) {
                if (flag) {
                    switch (refName) {
                        case 'diagnosisDialogComponent': // 诊断弹框
                            this.getPatientInfo();
                            break;
                    }
                }
            },
            /*** 诊断弹框 end ***/
            getPatientInfo() { //获取患者信息
                let para = {
                    id: this.logId,
                    webToken: this.$authInfo.webToken(),
                }
                this.$ajax.getAllInfo(para).then(res => {
                    this.patientList = res.data || {}
                }).catch(err => {})
            },
            getICDList() { //获取ICD列表
                this.ICDLoading = true
                let para = {
                    webToken: this.$authInfo.webToken(),
                }
                if (this.healthICDSearch) para.keyword = this.healthICDSearch
                this.$ajax.getIcdList(para).then(res => {
                    this.ICDlist = res.data.list || [];
                })
            },
            saveICDSearch(item) { //选择ICD检索与处方模板--点击列表
                this.drugSaveICDInput = item.icdName;
                this.drugSaveICDId = item.id;

                this.chooseICDSearchDialog = false;
            },
            getDrugClass() { //获取药品下拉列表
                let para = {
                    webToken: this.$authInfo.webToken(),
                }
                this.$ajax.getDrugClass(para).then(res => {
                    this.drugClassList = res.data;
                })
            },
            getWesternDataList({ page } = {}, store) { //获取药品列表
                page && (this.westernDataPage.current = page);

                this.shopId = String(store)

                this.dialogLoading = true;
                if (!this.isSub && this.$global.platform('zh') && this.paymentId == 2) {
                    /* --------- 珠海医院-医保付费 --------- */
                    // 医保时，个人用药列表置空
                    if (this.westernActiveName == '2') {
                        this.westernDataList = [];
                        this.dialogLoading = false;
                        return;
                    }

                    /* --- 医保付费 --- */
                    let params = {
                        pageSize: this.westernDataPage.size,
                        pageNo: this.westernDataPage.current
                    }

                    if (this.drugNameSearch) params.medicineName = this.drugNameSearch;

                    this.$ajax.getDrugListByZh(params).then(res => {
                        this.dialogLoading = false;

                        this.westernDataList = res.data.medicineListVOList || [];
                        this.westernDataPage.total = res.data.total;

                    }).catch(err => {
                        this.dialogLoading = false;
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                } else if (!this.isSub && this.$global.platform('lj') && store == 'ljyn') {
                    /* --------- 廉江医院-his --------- */
                    if (store == 'ljyn' && this.westernActiveName == '1') {
                        // 廉江医院-选择院内药房时 
                        let params = {
                            size: this.westernDataPage.size,
                            current: this.westernDataPage.current
                        }

                        if (this.drugNameSearch) params.drugName = this.drugNameSearch;

                        let api = this.isWesternChinese == 2 ? 'getWestDrugListByLj' : 'getCnDrugListByLj';
                        this.$ajax[api](params).then(res => {
                            this.dialogLoading = false;
                            this.westernDataList = res.data.list || [];
                            this.westernDataPage.total = res.data.total;
                            this.westernDataPage.page = res.data.pages;
                        }).catch(err => {
                            this.dialogLoading = false;
                            this.$message({
                                message: err.msg,
                                type: 'error',
                            })
                        })
                    } else {
                        this.westernDataList = [];

                        this.westernDataPage.current = 1;
                        this.westernDataPage.total = 0;

                        this.dialogLoading = false;
                    }
                } else {
                    let para = {
                        webToken: this.$authInfo.webToken(),
                        drugType: this.isWesternChinese,
                        isPublic: this.westernActiveName == '2' ? 1 : 0, //是否公共用药 0 公共 1个人
                        current: this.westernDataPage.current,
                        size: this.westernDataPage.size,
                    }
                    if (store != '') para.shopId = this.shopId
                    if (this.drugNameSearch && this.drugNameSearch != '') para.drugName = this.drugNameSearch;
                    if (this.drugClassSearch && this.drugClassSearch != '') para.classId = this.drugClassSearch;

                    this.$ajax.getDrugList(para).then(res => {
                        this.dialogLoading = false;
                        this.westernDataList = res.data.list || [];
                        this.westernDataPage.total = res.data.total;
                        this.westernDataPage.page = res.data.pages;
                    }).catch(err => {
                        this.dialogLoading = false;
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                }
            },
            changeWesternDataCurrent(val) { //药品列表分页
                this.westernDataPage.current = val;
                this.getWesternDataList({ page: val }, this.shopId);
            },
            saveDrugSingle(row) { //保存个人用药
                let para = {
                    id: row.id,
                    drugType: this.isWesternChinese,
                    webToken: this.$authInfo.webToken(),
                }
                this.$ajax.addPersonalDrug(para).then(res => {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                    })
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            deletePersonalDrug(row) { //删除个人用药
                this.$confirm(`是否删除？`, '删除', {
                    customClass: 'l-confirm',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                    this.$ajax.deletePersonalDrug({ id: row.drugTemplateId, webToken: this.$authInfo.webToken() }).then(res => {
                        this.getWesternDataList({ page: 1 }, this.shopId);
                        this.$message({
                            message: res.msg,
                            type: 'success',
                        })
                    }).catch(err => {
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                }).catch(() => {})
            },
            getPrescriptionTemplateList(store) { //获取西药药品列表--个人&共用模板
                this.dialogLoading = true;
                let para = {
                    webToken: this.$authInfo.webToken(),
                    prescriptionType: this.isWesternChinese,
                    isPublic: this.westernActiveName == '4' ? 1 : 0,
                }

                if (store != '') {
                    para.storeId = String(store)
                }

                this.$ajax.getPrescriptionTemplateList(para).then(res => {
                    this.westernModelList = res.data.list || []
                    this.dialogLoading = false;
                }).catch(err => {
                    this.dialogLoading = false;
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            deletePrescriptionTemplate(row) { //删除个人模板
                this.$confirm(`是否删除？`, '删除', {
                    customClass: 'l-confirm',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                    this.$ajax.deletePrescriptionTemplate({ id: row.id, webToken: this.$authInfo.webToken() }).then(res => {
                        this.getPrescriptionTemplateList('');
                        this.storeRadio = '';
                        this.$message({
                            message: res.msg,
                            type: 'success',
                        })
                    }).catch(err => {
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                }).catch(() => {})
            },
            getHisPrescription(store) { //获取西药药品列表--历史处方
                let para = {
                    webToken: this.$authInfo.webToken(),
                    prescriptionType: this.isWesternChinese, //1中药，2西药，不传查全部
                }
                this.dialogLoading = true;
                if (store != '') {
                    para.shopId = String(store)
                }
                this.$ajax.getOpenedPrescription(para).then(res => {
                    this.historyWesternList = res.data.list || []
                    this.dialogLoading = false;
                }).catch(err => {
                    this.dialogLoading = false;
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            getOpenedPrescription() { //获取西药药品列表--已开处方
                this.historyListLoading = true
                let para = {
                    webToken: this.$authInfo.webToken(),
                    prescriptionType: this.isWesternChinese, //1中药，2西药，不传查全部
                    inquiryPatientId: this.inquiryPatientId,
                    logId: this.logId,
                }
                this.$ajax.getOpenedPrescription(para).then(res => {
                    this.openWesternList = res.data.list || []
                    this.historyListLoading = false
                }).catch(err => {
                    this.historyListLoading = false
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            getOpenedPrescriptionInfo(row, checkType) { //获取药品列表--查看处方
                this.drugHisInfoList = row;
                this.prescriptionInfoListDialog = true;
                if (checkType == 2) {
                    this.isViewPrescription = true;
                    let para = {
                        webToken: this.$authInfo.webToken(),
                        id: row.id,
                    }
                    this.$ajax.getOpenedPrescriptionInfo(para).then(res => {
                        this.prescriptionInfoList = res.data.list || []
                        this.getPatientInfo();
                    })
                } else {
                    this.prescriptionInfoList = this.drugHisInfoList.drugList
                    this.isViewPrescription = false;
                }
            },
            checkAlready(row) {
                if (row) {
                    /* 检查重复 */
                    let flag = this.alreadydDrugList.filter(o => {
                        if (this.$global.platform('lj') && !row.storeId) {
                            return o.drugId == row.drugCode
                        } else {
                            return o.drugId == row.id
                        }
                    })

                    if (flag.length > 0) {
                        this.$util.message('请勿重复添加');
                        return false;
                    }

                    /* 检查数量 */
                    if (this.drugType == 2 && this.alreadydDrugList.length >= 5) {
                        this.$util.message('西药处方最多添加5个药品')
                        return false;
                    }

                    /* 检查来源 */
                    let drugItem = this.alreadydDrugList[0];
                    if (drugItem && ((row.storeId && row.storeId != drugItem.storeId) || (!row.storeId && drugItem.storeId != 0))) {
                        this.$util.message('生成处方的药品来源须一致');
                        return false;
                    }
                }

                return true;
            },
            // 打开开药弹框
            openUpdateDrug(isEdit, row = {}) {
                if (!isEdit && !this.checkAlready(row)) return;

                let params = {
                    isEdit: isEdit == 'edit',
                    editData: { ...row },
                    drugType: this.isWesternChinese,
                }

                if (params.isEdit) {
                    params.drugId = row.drugId;
                } else {
                    params.drugId = this.$global.platform('lj') && !row.storeId ? row.drugCode : row.id;
                }

                this.$nextTick(() => {
                    this.$refs.updateDrug && this.$refs.updateDrug.onOpen(params);
                })
            },
            // 保存用药
            saveDrugData(isEdit, data) {
                if (isEdit) {
                    let index = this.alreadydDrugList.findIndex(o => o.drugId == data.drugId);

                    if (index > -1) this.alreadydDrugList.splice(index, 1, data);
                } else {
                    this.alreadydDrugList.push(data);
                }

                if (!(this.$global.platform('zh') && this.paymentId == 2) && !this.alreadyHasHis) {
                    this.getReferencePrice();
                }

            },
            checkDrugSpeciFicationDetail(row) { // 用药规范--点击详情
                this.drugSpeciFicationDetailDialog = true;
                if (!this.isSub && this.$global.platform('zh') && this.paymentId == 2) {
                    /* 珠海医保--查看详情 */
                    let params = {
                        webToken: this.$authInfo.webToken(),
                        id: row.id
                    }

                    this.$ajax.getDrugDetailByZh(params).then(res => {
                        this.ficationDetailList = res.data || {};
                    })
                } else if (!this.isSub && this.$global.platform('lj') && this.storeRadio == 'ljyn') {
                    /* 廉江院内--查看详情 */
                    let params = {
                        drugType: this.isWesternChinese,
                        drugCode: row.drugCode
                    }

                    this.$ajax.getDrugDetailByLj(params).then(res => {
                        this.ficationDetailList = res.data;
                    })
                } else {
                    this.$ajax.getDrugSpeciFicationDetail({ id: row.id, webToken: this.$authInfo.webToken() }).then(res => {
                        this.ficationDetailList = res.data || {}
                    })
                }

            },
            delectPrescription(item) { //药品列表--开药列表--删除
                for (let j = 0; j < this.alreadydDrugList.length; j++) {
                    if (this.alreadydDrugList[j].drugId == item.drugId) {
                        this.alreadydDrugList.splice(j, 1);
                        this.getReferencePrice();
                    }
                }
            },

            getReferencePrice() { //计算参考价格
                if (this.alreadydDrugList.length <= 0) {
                    this.referencePrice = 0.00
                } else {
                    let num = 0
                    for (let i in this.alreadydDrugList) {
                        num += (Number(this.alreadydDrugList[i].drugPrice) * Number(this.alreadydDrugList[i].detailsNum));
                    }


                    this.referencePrice = this.isWesternChinese == 1 ? (Number(num) * Number(this.drugChineseTipsForm.prescriptionNum)).toFixed(2) : num.toFixed(2)
                }
            },
            addPrescriptionModel() { //药品弹框--生成处方
                /* --------- 检查来源 --------- */
                for (let k in this.alreadydDrugList) {
                    if (this.alreadydDrugList[k].storeId != this.alreadydDrugList[0].storeId) {
                        this.$util.message('请选择同一个药店的药品')
                        return false;
                    }
                }

                /* --------- 检查处方 --------- */
                if (this.alreadydDrugList.length <= 0) {
                    this.$util.message('请先开处方')
                    return false;
                }

                /* --------- 检查数量 --------- */
                if (this.isWesternChinese == 2 && this.alreadydDrugList.length > 5) {
                    this.$util.message('最多添加5个药方')
                    return false;
                }

                if (!this.isSub && this.$global.platform('zh') && this.paymentId == 2) {
                    /* --- 珠海医院-西药医保处方 --- */
                    // 生成处方前，需判断库存是否满足
                    let params = {
                        checkStockParamList: []
                    };
                    this.alreadydDrugList.forEach(item => {
                        params.checkStockParamList.push({
                            drugCommonCode: item.drugCommonCode,
                            name: item.drugName,
                            qty: item.detailsNum,
                            splitFlag: 0,
                        })
                    })

                    this.$ajax.checkDrugInventoryByZh(params).then(checkRes => {
                        this.submitDrugPerscription();
                    }).catch(err => {
                        this.$message.closeAll();
                        this.$message.error(err.msg);
                    })
                } else if (!this.isSub && this.alreadyHasHis) {
                    /* --------- 廉江医院-院内处方 --------- */
                    this.prescriptionTipsByLj()
                } else {
                    this.submitDrugPerscription();
                }
            },
            submitDrugPerscription() { // 西药--最终提交生成处方
                let para = {
                    webToken: this.$authInfo.webToken(),
                    prescriptionType: this.isWesternChinese,
                    id: this.isEditFlag ? this.drugOrderId : this.logId,
                    drugs: this.alreadydDrugList,
                    prescriptionPrice: this.referencePrice,
                    paymentMethod: this.paymentId == 2 ? 2 : 1
                }

                for (let k in this.alreadydDrugList) {
                    if (this.alreadydDrugList[k].storeId != this.alreadydDrugList[0].storeId) {
                        this.$message({
                            message: '请选择同一个药店的药品',
                            type: 'error',
                        })
                        return false;
                    }
                }

                if (this.isWesternChinese == 2) {
                    this.checkDrugPriceByHis(async () => {
                        this.addLoading = true
                        let api = ''
                        if (this.isEditFlag) {
                            api = 'updatePrescription';
                        } else {
                            api = 'addPrescription'
                        }

                        para.storeId = this.alreadydDrugList[0].storeId;
                        para.storeName = this.alreadydDrugList[0].storeName;

                        if (this.$global.platform('lj') && this.alreadydDrugList[0].storeId === 0) {
                            para.prescriptionPrice = this.hisDrugPrice;
                        }

                        var tempWindow = await this.createNewWin();
                        this.$ajax[api](para).then(res => {
                            this.gotoNewWin(tempWindow, res.data.esignUrl || '')
                            this.$util.message(res.msg, 'success')

                            this.alreadydDrugList = [];
                            this.getOpenedPrescription();
                            if (this.isEditFlag) {
                                this.westernMedicineDialog = false;
                                this.$emit('closed');
                            } else {
                                this.getPatientInfo()
                            }
                            this.referencePrice = 0;
                            this.hisDrugPrice = 0;
                            this.addLoading = false;

                        }).catch(err => {
                            this.addLoading = false;
                            this.$message({
                                message: err.msg,
                                type: 'error',
                            })
                        })
                    })
                } else {
                    // 中药 -- 生成处方
                    this.chineseDrugTipsDialog = true;

                    this.drugChineseTipsForm = Object.assign({}, this.$options.data.call(this).drugChineseTipsForm);

                    if (this.$global.platform('lj')) {
                        this.$ajax.getUsageOptionByLj({ dictType: '103' }).then(res => {
                            this.hisDrugUsageList = res.data || [];
                        }).catch(err => {
                            this.$util.message(err.msg);
                        })
                    }
                }
            },
            addChineseDrugTipsModel(formName) { //中药弹框--生成处方
                this.addLoading = true;

                this.checkDrugPriceByHis( () => {
                    this.$refs[formName].validate(async (valid) => {
                        if (valid) {
                            let para = {
                                webToken: this.$authInfo.webToken(),
                                prescriptionType: 1,
                                id: this.isEditFlag ? this.drugOrderId : this.logId,
                                drugs: this.alreadydDrugList,
                                prescriptionPrice: this.referencePrice,
                                prescriptionNum: this.drugChineseTipsForm.prescriptionNum,
                                prescriptionRequirements: this.drugChineseTipsForm.prescriptionRequirements,
                                prescriptionTaking: this.drugChineseTipsForm.prescriptionTaking,
                            }

                            para.storeId = this.alreadydDrugList[0].storeId;
                            para.storeName = this.alreadydDrugList[0].storeName;
                            para.paymentMethod = this.paymentId == 2 ? 2 : 1;

                            let api = ''
                            if (this.isEditFlag) {
                                api = 'updatePrescription';
                            } else {
                                api = 'addPrescription'
                            }

                            if (this.$global.platform('lj') && this.alreadydDrugList[0].storeId === 0) {
                                para.prescriptionPrice = this.hisDrugPrice;
                            } else {
                                let num = 0;
                                for (let i in this.alreadydDrugList) {
                                    num += (Number(this.alreadydDrugList[i].drugPrice) * Number(this.alreadydDrugList[i].detailsNum));
                                }

                                this.referencePrice = para.prescriptionPrice = this.isWesternChinese == 1 ? (Number(num) * Number(this.drugChineseTipsForm.prescriptionNum)).toFixed(2) : num.toFixed(2);
                            }

                            var tempWindow = await this.createNewWin();
                            this.$ajax[api](para).then(res => {
                                this.gotoNewWin(tempWindow, res.data.esignUrl || '')
                                this.$util.message(res.msg, 'success');

                                this.alreadydDrugList = [];
                                this.getOpenedPrescription();

                                if (!this.isEditFlag) { this.getPatientInfo() }
                                this.chineseDrugTipsDialog = false;
                                if (this.isEditFlag) {
                                    this.westernMedicineDialog = false;
                                    this.$emit('closed');
                                }
                                this.referencePrice = 0;
                                this.hisDrugPrice = 0;
                                this.$nextTick(() => {
                                    this.$refs.drugChineseTipsForm && this.$refs.drugChineseTipsForm.resetFields();
                                })
                                this.addLoading = false;
                            }).catch(err => {
                                this.addLoading = false
                                this.$message({
                                    message: err.msg,
                                    type: 'error',
                                })
                            })
                        } else {
                            this.addLoading = false;
                        }
                    })
                })
            },
            deletePrescription(item) { //药品弹框--删除生成的处方
                this.$confirm(`是否删除？`, '删除', {
                    customClass: 'l-confirm',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                    let para = {
                        webToken: this.$authInfo.webToken(),
                        id: item.id,
                    }
                    this.$ajax.deletePrescription(para).then(res => {
                        this.getOpenedPrescription();
                        this.getPatientInfo();
                        this.$message({
                            message: res.msg,
                            type: 'success',
                        })
                    }).catch(err => {
                        this.$message({
                            message: err.msg,
                            type: 'error',
                        })
                    })
                }).catch(() => {})
            },
            getDrugUsageList(chinaType) { //药品弹框--获取药品用法
                if (!this.isSub && (this.drugIsHis && this.isWesternChinese == '2')) {
                    // 获取his药品频率
                    this.$ajax.getUsageOptionByLj({ dictType: '51' }).then(res => {
                        this.drugUsageList = res.data || [];
                    })
                } else {
                    let para = {
                        webToken: this.$authInfo.webToken(),
                    }

                    if (this.isWesternChinese == '1' && (chinaType != 3 && chinaType != 4)) {
                        para.usageType = 2
                    } else if (this.isWesternChinese == '2' && (chinaType != 3 && chinaType != 4)) {
                        para.usageType = 1
                    } else if (this.isWesternChinese == '1' && chinaType == 3) {
                        para.usageType = 3
                    } else if (this.isWesternChinese == '1' && chinaType == 4) {
                        para.usageType = 4
                    }

                    this.$ajax.getDrugUsageList(para).then(res => {
                        this.drugUsageList = res.data.list
                    })
                }
            },
            openPrescriptionDialog() { //药品弹框--打开另存个人模板
                if (this.alreadydDrugList.length > 0) {
                    for (let k in this.alreadydDrugList) {
                        if (this.alreadydDrugList[k].storeId != this.alreadydDrugList[0].storeId) {
                            this.$message({
                                message: '请选择同一个药店的药品',
                                type: 'error',
                            })
                            return false;
                        }
                    }
                    this.addPrescriptionTemplateDialog = true
                    this.drugSaveICDInput = ''
                    this.drugSaveICDId = ''
                    this.drugSaveInput = ''
                    this.drugRemrakInput = ''
                } else {
                    this.$message.closeAll();
                    this.$message({
                        message: '请先开处方',
                        type: 'error',
                    })
                }
            },
            quoteDrugDetail(row, quoteType) { //西药处方--引用个人模板
                this.alreadydDrugList = []
                if (quoteType == 1) {
                    for (let i in row.drugList) {
                        if (this.isWesternChinese == 2) {
                            this.alreadydDrugList.push({
                                detailsConsumption: row.drugList[i].detailsConsumption,
                                detailsConsumptionUnit: row.drugList[i].detailsConsumptionUnit,
                                detailsFrequencyStr: row.drugList[i].detailsFrequencyStr,
                                detailsFrequency: row.drugList[i].detailsFrequency,
                                detailsDay: row.drugList[i].detailsDay,
                                detailsNum: row.drugList[i].detailsNum,
                                detailsUsage: row.drugList[i].detailsUsage,
                                detailsEntrust: row.drugList[i].detailsEntrust,
                                drugName: row.drugList[i].drugName,
                                drugId: row.drugList[i].id,
                                drugPrice: row.drugList[i].drugPrice,
                                storeId: row.drugList[i].storeId,
                                storeName: row.drugList[i].storeName,
                            })
                        } else {
                            this.alreadydDrugList.push({
                                detailsConsumption: row.drugList[i].detailsConsumption,
                                detailsConsumptionUnit: row.drugList[i].detailsConsumptionUnit,
                                detailsUsage: row.drugList[i].detailsUsage,
                                detailsNum: row.drugList[i].detailsNum,
                                drugName: row.drugList[i].drugName,
                                drugId: row.drugList[i].id,
                                drugPrice: row.drugList[i].drugPrice,
                                storeId: row.drugList[i].storeId,
                                storeName: row.drugList[i].storeName,
                            })

                        }
                    }

                    this.getPrescriptionTemplateList('');
                    this.getReferencePrice()
                } else {
                    for (let j in row.detailsResps) {
                        if (this.isWesternChinese == 2) {
                            this.alreadydDrugList.push({
                                detailsConsumption: row.detailsResps[j].detailsConsumption,
                                detailsConsumptionUnit: row.detailsResps[j].detailsConsumptionUnit,
                                detailsFrequencyStr: row.detailsResps[j].detailsFrequencyStr,
                                detailsFrequency: row.detailsResps[j].detailsFrequency,
                                detailsDay: row.detailsResps[j].detailsDay,
                                detailsNum: row.detailsResps[j].detailsNum,
                                detailsUsage: row.detailsResps[j].detailsUsage,
                                detailsEntrust: row.detailsResps[j].detailsEntrust,
                                drugName: row.detailsResps[j].drugName,
                                drugId: row.detailsResps[j].id,
                                drugPrice: row.detailsResps[j].drugPrice,
                                storeId: row.detailsResps[j].storeId,
                                storeName: row.detailsResps[j].storeName,
                            })
                        } else {
                            this.alreadydDrugList.push({
                                detailsConsumption: row.detailsResps[j].detailsConsumption,
                                detailsConsumptionUnit: row.detailsResps[j].detailsConsumptionUnit,
                                detailsUsage: row.detailsResps[j].detailsUsage,
                                detailsNum: row.detailsResps[j].detailsNum,
                                drugName: row.detailsResps[j].drugName,
                                drugId: row.detailsResps[j].id,
                                drugPrice: row.detailsResps[j].drugPrice,
                                storeId: row.detailsResps[j].storeId,
                                storeName: row.detailsResps[j].storeName,
                            })
                        }
                    }

                    this.getHisPrescription('')
                    this.getReferencePrice()
                }
            },
            saveAnotherModel() { //药品弹框--新增个人模板、另存模板
                let para = {
                    webToken: this.$authInfo.webToken(),
                    prescriptionName: this.drugSaveInput,
                    prescriptionType: this.isWesternChinese,
                    diagnosisId: this.drugSaveICDId,
                    drugs: this.alreadydDrugList,
                    prescriptionPrice: this.referencePrice,
                }
                if (this.drugRemrakInput) { para.remarks = this.drugRemrakInput }

                para.storeId = this.alreadydDrugList[0].storeId;
                para.storeName = this.alreadydDrugList[0].storeName;

                this.$ajax.addPrescriptionTemplate(para).then(res => {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                    });
                    this.addPrescriptionTemplateDialog = false;
                    this.getPrescriptionTemplateList('');
                    this.storeRadio = '';
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: 'error',
                    })
                })
            },
            openDialog(dialogName) {
                if (dialogName == 'chooseICDSearchDialog') { //健康指导--选择ICD检索
                    this.chooseICDSearchDialog = true;
                    this.ICDTypeName = 'drug';
                    this.healthICDSearch = '';
                    this.ICDlist = []
                }
            },
            closeDialog(dialogName) { //关闭弹框
                if (dialogName == 'westernMedicineDialog') { //西药弹框
                    this.westernMedicineDialog = false;
                    this.isWesternChinese = '';
                    if (!this.isEditFlag) { this.getPatientInfo(); }

                    Object.assign(this.$data, this.$options.data.call(this));
                    this.$emit('closed');
                }
                if (dialogName == 'prescriptionInfoListDialog') { //处方历史--查看详情
                    this.prescriptionInfoListDialog = false;
                }

                if (dialogName == 'addPrescriptionTemplateDialog') { //处方历史--另存個人模板弹框
                    this.addPrescriptionTemplateDialog = false;
                }
            },
            check(val) {
                let params = {
                    id: val.id,
                    resource: 4
                };

                this.$refs.pdfDialog && this.$refs.pdfDialog.onOpen(params);
            },
            getStoreList() {
                this.$ajax.getStoreList().then(res => {
                    this.storeList = res.data || []
                })
            },
            // 切换药店
            changeStore(shopId) {
                this.storeRadio = shopId || '';

                if (shopId == 'ljyn') this.drugClassSearch = '';

                switch (this.westernActiveName) {
                    case '1':
                    case '2':
                        this.getWesternDataList({ page: 1 }, this.storeRadio);
                        break;
                    case '3':
                    case '4':
                        if (this.$global.platform('lj') && this.storeRadio == 'ljyn' && !this.isSub) {
                            this.westernModelList = [];
                        } else {
                            this.getPrescriptionTemplateList(this.storeRadio);
                        }
                        break;
                    case '5':
                        if (this.$global.platform('lj') && this.storeRadio == 'ljyn' && !this.isSub) {
                            this.historyWesternList = [];
                        } else {
                            this.getHisPrescription(this.storeRadio);
                        }
                        break;
                }
            },
            // 廉江院内药房开处方提示
            prescriptionTipsByLj() {
                let h = this.$createElement;
                let txt = h('div', {}, [
                    h('span', {}, ' 该处方所属药房为院内药房，请提醒患者：由于互联网医院不支持线上支付院内处方药品费，'),
                    h('span', { style: { color: '#f00' } }, '请今天内，自行到院内窗口缴费并到相应药房窗口取药'),
                ]);

                this.$confirm(txt, '生成处方温馨提示', {
                    customClass: 'l-confirm',
                    confirmButtonText: '患者已知晓',
                    cancelButtonText: '取消',
                }).then(() => {
                    this.submitDrugPerscription();
                }).catch(() => {})
            },
            checkDrugPriceByHis(fn) {
                if (this.$global.platform('lj') && this.alreadydDrugList[0].storeId === 0) {
                    /* --------- 廉江医院-检查药品库存 --------- */
                    let params = {
                        detailInfo: []
                    };
                    this.addLoading = true;
                    this.alreadydDrugList.forEach(item => {
                        let count = this.isWesternChinese == 1 ? Number(item.detailsNum) * Number(this.drugChineseTipsForm.prescriptionNum) : item.detailsNum;

                        params.detailInfo.push({
                            detailId: item.drugId,
                            detailName: item.drugName,
                            detailCount: count,
                        })
                    })

                    this.$ajax.checkDrugInventoryByLj(params).then(checkRes => {
                        this.addLoading = false;
                        this.hisDrugPrice = checkRes.totalPrice;
                        if (fn) fn();
                    }).catch(err => {
                        this.addLoading = false;
                        this.$message.closeAll();
                        this.$message.error(err.msg);
                    })
                } else {
                    if (fn) fn();
                }
            },
            checkDrugDisable(row, isEdit) {
                if (this.$global.isMental) { // 检查禁用药品
                    this.$ajax.checkDrugDisable({
                        drugId: row.id || row.drugId
                    }).then(res => {
                        // this.prescriptionDialog(row, isEdit)
                        this.openUpdateDrug(isEdit, row)
                    }).catch(err => {
                        this.$util.message(err.msg);
                    })
                } else {
                    // this.prescriptionDialog(row, isEdit)
                    this.openUpdateDrug(isEdit, row)

                }
            },
            async createNewWin() {
                var tempWindow = null;
                if (await this.$util.notSilentCa()) {
                    if (this.$util.notSilentCa()) {
                        tempWindow = window.open('', '_blank');
                        tempWindow.document.title = 'e签宝(加载中,请勿关闭)'
                    }
                }
                return tempWindow;
            },
            gotoNewWin(tempWindow, url = '') {
                if (!tempWindow) return;
                if (url) {
                    tempWindow.location.href = url;
                } else {
                    tempWindow && tempWindow.close();
                }
            }
        },
        watch: {
            alreadydDrugList(newList, oldList) {
                if (newList.length > 0) {
                    this.alreadyHasHis = newList[0].storeId === 0 || newList[0].storeId == '0';
                } else {
                    this.alreadyHasHis = false;
                }
            }
        }
    }
</script>

<style lang="scss" src="@/style/page/vedio.scss"></style>